﻿using System;
using System.Diagnostics;

using Ycg.Logging.Layout;

namespace Ycg.Logging.Targets
{
    internal class EventLogTarget : LogTarget
    {
        private EventLog _eventLog;
        private bool _isFirstInvoke = true;

        public EventLogTarget()
        {
            this.LogName = "Application";
            this.MachineName = Environment.MachineName;
            this.Source = AppDomain.CurrentDomain.FriendlyName;
            this._eventLog = new EventLog(this.LogName, this.MachineName, this.Source);
        }

        public string Source { get; set; }
        public string LogName { get; set; }
        public string MachineName { get; set; }

        public void Install()
        {
            if (EventLog.SourceExists(this.Source, this.MachineName))
            {
                string currentLogName = EventLog.LogNameFromSourceName(this.Source, this.MachineName);
                if (currentLogName != this.LogName)
                {
                    EventLog.DeleteEventSource(this.Source, this.MachineName);
                    var eventSource = new EventSourceCreationData(this.Source, this.LogName) { MachineName = this.MachineName };
                    EventLog.CreateEventSource(eventSource);
                }
            }
            else
            {
                var eventSource = new EventSourceCreationData(this.Source, this.LogName) { MachineName = this.MachineName };
                EventLog.CreateEventSource(eventSource);
            }
        }

        public void Uninstall()
        {
            EventLog.DeleteEventSource(this.Source, this.MachineName);
        }

        public override void Write(LogInfo logInfo)
        {
            if (this._isFirstInvoke)
            {
                this.Install();
                this._isFirstInvoke = false;
            }


            //这边有个问题
            //就是实现NLog记录日志的等级问题
            //当记录所有等级的Log
            //当记录大于Error等级的Log

            EventLogEntryType logEntryType = EventLogEntryType.Information;
            if (logInfo.LogLevel == LogLevel.Error)
            {
                logEntryType = EventLogEntryType.Error;
            }
            else if (logInfo.LogLevel == LogLevel.Info)
            {
                logEntryType = EventLogEntryType.Information;
            }
            else if (logInfo.LogLevel == LogLevel.Warning)
            {
                logEntryType = EventLogEntryType.Warning;
            }

            this._eventLog.WriteEntry(new DefaultLayout(logInfo).ToString(), logEntryType);
        }
    }
}
